import {Injectable, Output} from '@angular/core';
import {ActivatedRouteSnapshot, CanActivate, CanActivateChild, Router, RouterStateSnapshot} from "@angular/router";
import {Observable} from "rxjs/Observable";
import {AuthService} from "./auth.service";
import {AppConstants, Components} from "../constants/constants";
import "rxjs/operator/toPromise";
import {DataStorageUtil} from "../util/data-storage-util";
declare var $:any;

@Injectable()
export class AuthGuardService implements CanActivate,CanActivateChild{

  constructor(
    private authService: AuthService,
    private dataStorage:DataStorageUtil,
    private router: Router
  ) {
  }
  canActivate(route: ActivatedRouteSnapshot,
              state: RouterStateSnapshot): Observable<boolean>|Promise<boolean>|boolean {
    let url: string = state.url;
    return this.checkLogin(url) && this.checkPermission(url);
  }

  canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean>|Promise<boolean>|boolean {
    return this.canActivate(childRoute,state);
  }

  private checkLogin(url: string) : boolean {
    let isLogin = this.dataStorage.get(AppConstants.isLogin);
    if (!!isLogin && AppConstants.loginSucess == isLogin) {
      return true;
    } else {
      this.authService.redirectUrl = url;
      this.redirect();
      return false;
    }
  }

  private checkPermission(url: string) : boolean{
    return true;
  }


  private redirect() {
    this.router.navigate([Components.authenComponent]);
  }
}
